const axios = require('axios');

const baseURL = 'http://localhost:7172';

// 测试钱包地址（之前创建代币时使用的）
const testWallet = {
  address: '0xd936abB827adE4B72B3d89b3e73e9dF22c5F6Bb2',
  privateKey: '0x9a21f9e6e4b3c7d8f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4'
};

// 要测试的代币信息
const testToken = {
  launchId: 1,  // 替换为实际的代币ID
  tokenAddress: '0x22F18e6edfF9E6F85E6a58e50c8c9b8Fb9c4D5E6',  // 替换为实际的代币合约地址
  amount: 1000  // 要出售的代币数量
};

async function testSellFlow() {
  console.log('🔍 开始测试代币出售流程...\n');
  
  try {
    // 1. 首先检查代币信息
    console.log('1. 获取代币信息...');
    const tokenInfo = await axios.get(`${baseURL}/api/bsc/tokens/${testToken.launchId}`);
    console.log('✅ 代币信息:', {
      name: tokenInfo.data.name,
      symbol: tokenInfo.data.symbol,
      tokenAddress: tokenInfo.data.tokenAddress,
      currentPrice: tokenInfo.data.currentPrice,
      totalSupply: tokenInfo.data.totalSupply,
      totalContributions: tokenInfo.data.totalContributions
    });
    console.log('');
    
    // 2. 预览出售交易
    console.log('2. 预览出售交易...');
    const previewData = {
      launchId: testToken.launchId,
      userAddress: testWallet.address,
      tokenAmount: testToken.amount,
      type: 'sell'
    };
    
    const preview = await axios.post(`${baseURL}/api/bsc/tokens/preview`, previewData);
    console.log('✅ 出售预览:', {
      tokenAmount: preview.data.tokenAmount,
      bnbAmount: preview.data.bnbAmount,
      newPrice: preview.data.newPrice,
      priceImpact: preview.data.priceImpact,
      userTokenBalance: preview.data.userTokenBalance
    });
    console.log('');
    
    // 3. 执行出售交易
    console.log('3. 执行出售交易...');
    const sellData = {
      launchId: testToken.launchId,
      sellerAddress: testWallet.address,
      sellerPrivateKey: testWallet.privateKey,
      tokenAmount: testToken.amount
    };
    
    const sellResult = await axios.post(`${baseURL}/api/bsc/tokens/sell`, sellData);
    console.log('✅ 出售成功!', {
      transactionHash: sellResult.data.transactionHash,
      tokensSold: sellResult.data.tokensSold,
      bnbReceived: sellResult.data.bnbReceived,
      newPrice: sellResult.data.newPrice,
      gasUsed: sellResult.data.gasUsed
    });
    console.log('');
    
    // 4. 再次检查代币信息确认更新
    console.log('4. 确认代币信息更新...');
    const updatedTokenInfo = await axios.get(`${baseURL}/api/bsc/tokens/${testToken.launchId}`);
    console.log('✅ 更新后的代币信息:', {
      currentPrice: updatedTokenInfo.data.currentPrice,
      totalContributions: updatedTokenInfo.data.totalContributions
    });
    
    console.log('\n🎉 代币出售流程测试完成!');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.response?.data || error.message);
    if (error.response?.data?.details) {
      console.error('详细错误:', error.response.data.details);
    }
  }
}

// 创建测试代币（如果需要）
async function createTestToken() {
  console.log('🎯 创建测试代币...\n');
  
  try {
    const tokenData = {
      name: "Test Sell Token",
      symbol: "TST",
      description: "Token for testing sell functionality",
      targetAmount: 10,
      creatorPrivateKey: testWallet.privateKey,
      website: "https://example.com",
      twitter: "https://twitter.com/example",
      telegram: "https://t.me/example"
    };
    
    const result = await axios.post(`${baseURL}/api/bsc/tokens`, tokenData);
    console.log('✅ 测试代币创建成功:', {
      launchId: result.data.data.launchId,
      tokenAddress: result.data.data.tokenAddress,
      transactionHash: result.data.data.transactionHash
    });
    
    return {
      launchId: result.data.data.launchId,
      tokenAddress: result.data.data.tokenAddress
    };
    
  } catch (error) {
    console.error('❌ 创建代币失败:', error.response?.data || error.message);
    return null;
  }
}

// 购买代币（为出售做准备）
async function buyTokenForTest(launchId) {
  console.log('💰 购买测试代币...\n');
  
  try {
    const buyData = {
      launchId: launchId,
      buyerAddress: testWallet.address,
      buyerPrivateKey: testWallet.privateKey,
      bnbAmount: 0.01  // 购买 0.01 BNB 的代币
    };
    
    const result = await axios.post(`${baseURL}/api/bsc/tokens/buy`, buyData);
    console.log('✅ 代币购买成功:', {
      transactionHash: result.data.transactionHash,
      tokensBought: result.data.tokensBought,
      bnbSpent: result.data.bnbSpent,
      newPrice: result.data.newPrice
    });
    
    return true;
    
  } catch (error) {
    console.error('❌ 购买代币失败:', error.response?.data || error.message);
    return false;
  }
}

// 完整测试流程
async function fullTestFlow() {
  console.log('🚀 开始完整的代币出售测试流程...\n');
  
  // 1. 创建测试代币
  const token = await createTestToken();
  if (!token) {
    console.log('❌ 无法创建测试代币，退出测试');
    return;
  }
  
  // 等待一些时间让交易确认
  console.log('⏳ 等待代币创建交易确认...');
  await new Promise(resolve => setTimeout(resolve, 3000));
  
  // 2. 购买代币
  const buySuccess = await buyTokenForTest(token.launchId);
  if (!buySuccess) {
    console.log('❌ 无法购买代币，退出测试');
    return;
  }
  
  // 等待一些时间让交易确认
  console.log('⏳ 等待购买交易确认...');
  await new Promise(resolve => setTimeout(resolve, 3000));
  
  // 3. 更新测试代币信息
  testToken.launchId = token.launchId;
  testToken.tokenAddress = token.tokenAddress;
  
  // 4. 测试出售
  await testSellFlow();
}

// 根据命令行参数决定运行哪个测试
const command = process.argv[2];

if (command === 'full') {
  fullTestFlow();
} else if (command === 'sell') {
  testSellFlow();
} else {
  console.log('使用方法:');
  console.log('  node test-sell-fixed.js full  - 完整测试流程（创建代币->购买->出售）');
  console.log('  node test-sell-fixed.js sell  - 仅测试出售功能（需要先修改代币信息）');
}
